import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/config/address.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/tools_base/widget/LoadingWidget.dart' as l;

import '../assets_tool/lang.dart';
import '../hj_page/web_page/h5_page.dart';

extension IntWidget on int {
  Widget get sizeBoxH {
    return SizedBox(
      height: toDouble(),
    );
  }

  Widget get sizeBoxW {
    return SizedBox(
      width: toDouble(),
    );
  }

  Widget get line {
    return Container(
      height: toDouble(),
      color: Colors.white.withOpacity(.1),
    );
  }

  Widget get lineV {
    return Container(
      height: toDouble(),
      width: 0.5,
      color: Colors.white.withOpacity(.1),
    );
  }

  Widget get sliverLine {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16),
        height: toDouble(),
        color: Colors.white.withOpacity(.1),
      ),
    );
  }

  Widget get sliverSizeBoxH {
    return SliverToBoxAdapter(
      child: SizedBox(height: toDouble()),
    );
  }
}

extension DoubleWidget on double {
  Widget get sizeBoxH {
    return SizedBox(
      height: toDouble(),
    );
  }

  Widget get sizeBoxW {
    return SizedBox(
      width: toDouble(),
    );
  }

  Widget get line {
    return Container(
      height: toDouble(),
      color: Colors.white.withOpacity(.1),
    );
  }

  Widget get sliverLine {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16),
        height: toDouble(),
        color: Colors.white.withOpacity(.1),
      ),
    );
  }
}

extension IntFormat on int? {
  //人性化数量
  String get humanizeFormat {
    int value = this ?? 0;
    if (value <= 0 || value.isNaN) {
      return '0';
    } else if (value > 0 && value < 1000) {
      return value.toString();
    } else if (value >= 1000 && value < 10000) {
      String format = (value / 1000).toStringAsFixed(1);
      return '${format}k';
    } else if (value >= 10000 && value < 100000000) {
      String format = (value / 10000).toStringAsFixed(1);
      return '${format}w';
    } else {
      String format = (value / 100000000).toStringAsFixed(1);
      return '$format${Lang.BILLION}';
    }
  }

  String humanizeFormatDefault(String? defValue) {
    int value = this ?? 0;
    if (value <= 0 || value.isNaN) {
      return defValue ?? '0';
    } else {
      return humanizeFormat;
    }
  }

  String get timeMSFormat {
    var duration = Duration(milliseconds: ((this ?? 0) * 1000));

    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(Duration.minutesPerHour));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(Duration.secondsPerMinute));

    var str = "$twoDigitMinutes:$twoDigitSeconds";

    if (duration.inHours == 0) {
      return str;
    }
    var hour = duration.inHours.toString().padLeft(2, "0");
    return "$hour:$str";
  }
}

class WidgetUtils {
  WidgetUtils._internal();

  static WidgetUtils? instance;

  static getInstance() {
    instance ??= WidgetUtils._internal();
    return instance;
  }

  factory WidgetUtils() => getInstance();

  Widget buildElevatedButton(String text,
      {Color? bg = AppColors.primary51Color,
      Color textColor = Colors.white,
      double padding = 0,
      double margin = 0,
      double height = 44,
      double width = double.infinity,
      double bottom = 0,
      double opacity = 1,
      double textSize = 16,
      FontWeight fontWeight = FontWeight.w600,
      VoidCallback? onPressed}) {
    return Opacity(
      opacity: opacity,
      child: Container(
        height: height,
        width: width,
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: padding ?? 0, right: padding ?? 0),
        margin: EdgeInsets.only(
          left: margin,
          right: margin,
          bottom: bottom,
        ),
        decoration: const BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(40)), color: AppColors.primary51Color),
        child: Text(
          text,
          style: TextStyle(fontSize: textSize, color: Colors.white, fontWeight: fontWeight),
        ),
      ),
    );
  }

  Widget buildTitle(String title, {double padding = 12, double fontSize = 14}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 8,
          height: 22,
          decoration: const BoxDecoration(
              color: AppColors.primary51Color,
              borderRadius: BorderRadius.only(topRight: Radius.circular(4), bottomRight: Radius.circular(4))),
        ),
        SizedBox(
          width: padding,
        ),
        Text(
          title,
          style: TextStyle(
            color: AppColors.primary51Color,
            fontSize: fontSize,
          ),
        )
      ],
    );
  }

  buildTips(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Text(
          "支付遇到问题请联系",
          style: TextStyle(fontSize: 12, color: Color.fromRGBO(161, 162, 168, 1)),
        ),
        const SizedBox(
          width: 8,
        ),
        GestureDetector(
            onTap: () async {
              l.LoadingWidget loadingWidget = l.LoadingWidget();
              loadingWidget.show();
              dynamic data = await MineService.fetchCustomService();
              loadingWidget.cancel();

              Get.to(
                  H5Page(
                    url: "${Address.baseApiPath}/$data",
                    title: "在线客服",
                  ),
                  opaque: false);
            },
            child: const Text(
              "在线客服",
              style: TextStyle(fontSize: 12, color: AppColors.primaryColor3),
            )),
      ],
    );
  }

  Widget buildOutlineButton(String text, double width, double height, Color lineColor,
      {Color? bg, Color textColor = Colors.white, double textSize = 14, VoidCallback? onPressed}) {
    return OutlinedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.r),
        ),
        side: BorderSide(color: lineColor, width: 1.r),
        backgroundColor: bg,
        minimumSize: Size(width, height),
        maximumSize: Size(width, height),
        padding: EdgeInsets.zero,
      ),
      child: Text(
        text,
        style: TextStyle(fontSize: textSize.sp, color: textColor, fontWeight: FontWeight.w600),
      ),
    );
  }

  void clickCopy(String value) {
    if (value.isNotEmpty) {
      Clipboard.setData(ClipboardData(text: value));
      showToast("复制成功");
    }
  }
}

TextStyle textStyle(double fontSize, Color color, FontWeight fontWeight, {bool isNeedThrough = false}) {
  return TextStyle(
      color: color, fontSize: fontSize.toDouble(), fontWeight: fontWeight, decoration: isNeedThrough ? TextDecoration.lineThrough : null);
}

//背景dialog弹窗包裹
Widget DiglogWidget(Widget child) {
  return GestureDetector(
    onTap: () => Get.back(),
    child: Material(
      color: Colors.transparent,
      child: GestureDetector(
        onTap: () => null,
        child: Center(
          child: child,
        ),
      ),
    ),
  );
}

//渐变边框
class GradientBorderPainter extends CustomPainter {
  final double strokeWidth;
  final BorderRadiusGeometry radius;
  final Gradient gradient;

  GradientBorderPainter({
    required this.strokeWidth,
    required this.radius,
    required this.gradient,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Rect.fromLTWH(0, 0, size.width, size.height);
    final paint = Paint()
      ..shader = gradient.createShader(rect)
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke;

    final path = Path.combine(PathOperation.difference, Path()..addRRect(radius.resolve(TextDirection.ltr).toRRect(rect)),
        Path()..addRRect(radius.resolve(TextDirection.ltr).toRRect(rect.deflate(strokeWidth / 2))));

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

bool textExceedMaxLines(String text, TextStyle textStyle, int maxLine, double maxWidth) {
  TextSpan textSpan = TextSpan(text: text, style: textStyle);
  TextPainter textPainter = TextPainter(text: textSpan, maxLines: maxLine, textDirection: TextDirection.ltr);
  textPainter.layout(maxWidth: maxWidth);
  print(textPainter.height);
  if (textPainter.didExceedMaxLines) {
    return true;
  }
  return false;
}
